<template>
    <el-dialog :model-value="props.addEditUserDialog" :title="title === 'add' ? '添加用户' : '修改用户'" :before-close="closeDialog">
      <el-form ref="ruleFormRef" :model="form" label-width="auto" :rules="formRules.rules">
         <el-form-item label="用户名" prop="username">
           <el-input v-model="form.username" :disabled="title === 'add' ? false : true"/>
         </el-form-item>
  
         <el-form-item label="密码" prop="password" v-if="title == 'add'">
           <el-input v-model="form.password" type="password"/>
         </el-form-item>
  
         <el-form-item label="邮箱" prop="email" >
           <el-input v-model="form.email" />
         </el-form-item>
  
         <el-form-item label="手机" prop="mobile">
           <el-input v-model="form.mobile" />
         </el-form-item>
      </el-form>
  
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="onSubmit(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref, watch } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { AddUserFnc, EditUserFnc, GetUserInfoFnc } from '@/api/user'  
  
    const props = defineProps({
      addEditUserDialog: {type: Boolean, required: true},
      typeFlag: {type: String, required: true},
      pageNow: {type: Number, required: true},
      pageSize: {type: Number, required: true},
      userID: {type: Number, required: true}
    })
  
    const emit = defineEmits(['showDialog', 'init'])

    const title = ref('')
    const ruleFormRef = ref<FormInstance>()
    const objForm = ref({}) // 复制对象  用做修改对象时做比较 是否有做修改  
  
    // 自定义验证邮箱的规则
    const checkEmail = (rule: any, value: any, cb: Function) => {
      console.log(rule)
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
  
    // 自定义验证手机号的规则
    const checkMobile = (rule: any, value: any, cb: Function) => {
      console.log(rule)
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
  
    // 表单数据
    const form = reactive({
      username: '',
      password: '',
      email: '',
      mobile: '',
    })
  
    // 表单验证规则
    const formRules = reactive({
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 5, message: '长度在3-5个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 7, message: '长度在3-7个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkMobile, trigger: 'blur'}
        ]
      }
    })

    // typFlage决定是 添加用户 还是 修改用户   userID决定 打开哪个用户的盒子
    watch([() => props.typeFlag, () => props.userID], async ([newType, newUserID]) => {
      title.value = newType
      if(newType === 'edit') {
        const res = await GetUserInfoFnc(newUserID)
        if(res.data.meta.status === 200) {
           form.username = res.data.data.username,
           form.email = res.data.data.email,
           form.mobile = res.data.data.mobile
           objForm.value = {...form}
        }
      }
    })

    // 关闭dialog
    const closeDialog = () => {
      emit('showDialog', false) 
      form.username = ''
      form.password = ''
      form.email = ''
      form.mobile = ''
    }
  
    // 公共消息
    const publicMsg = (msg: string) => {
      ElMessage({type: 'success', message: msg, duration: 1000, onClose: () => {
        emit('showDialog', false)
        emit('init', props.pageNow, props.pageSize) 
        form.username = ''
        form.password = ''
        form.email = ''
        form.mobile = ''
      }})
    }

    // 提交表单
    const onSubmit = async (formEl: FormInstance | undefined) => {
      console.log(formEl)
      if(!formEl) return  
      await formEl.validate(async (valid) => {
        if(valid) {
          if(title.value === 'add') { // 添加用户
            const res =  await AddUserFnc(form)
            if(res.data.meta.status === 201) {
               publicMsg(res.data.meta.msg)
            } 
          } else { // 修改用户
            if(JSON.stringify(objForm.value) === JSON.stringify(form)) { // 未做修改
              emit('showDialog', false)
              return
            } else { // 修改了
              const res =  await EditUserFnc(props.userID, form)
              if(res.data.meta.status === 200) {
                publicMsg(res.data.meta.msg)
              }
            }
          }
        }
      })
    }
  </script>